#include "epoll_handler.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>

bool EpollHandler::EpollInit()
{
	epollFd = epoll_create(FDSIZE);
	if(epollFd == -1) {
		printf("epoll create failed.\n");
		return false;
	}

	return true;
}

void EpollHandler::EpollUinit()
{
	free(events);
	close(epollFd);
}

int EpollHandler::WaitEpoll()
{
	//memset(events, 0, sizeof(epoll_event) * EPOLLEVENTS);
	return epoll_wait(epollFd, events, EPOLLEVENTS , -1);
}

int EpollHandler::CheckEvent(int num, int action)
{
	int srcFd = events[num].data.fd;
	if ((events[num].events & (EPOLLERR|EPOLLHUP|EPOLLPRI))) {
		printf("CheckEvent get error.\n");
		return -1;
	}

	if((events[num].events & action)) {
		return srcFd;
	}	
	return -1;
}

int EpollHandler::CheckInEvent(int num)
{
	return CheckEvent(num, EPOLLIN);
}

int EpollHandler::CheckOutEvent(int num)
{
	return CheckEvent(num, EPOLLOUT);
}

bool EpollHandler::CtlEvent(int option, int fd, int state)
{
	struct epoll_event event;
	//设置events什么时候触发
	event.events = state;
	event.data.fd = fd;
	int ret = epoll_ctl(epollFd, option, fd, &event);
	if(ret == -1) {
		printf("Change Event failed.\n");
		return false;
	}
	return true;
}

bool EpollHandler::AddEvent(int fd, int state)
{
	return CtlEvent(EPOLL_CTL_ADD, fd, state);
}

bool EpollHandler::DeleteEvent(int fd, int state)
{
	return CtlEvent(EPOLL_CTL_DEL, fd, state);
}

bool EpollHandler::ModifyEvent(int fd, int state)
{
	return CtlEvent(EPOLL_CTL_MOD, fd, state);
}

